// pages/twenty_four_math/twenty_four_math.js
const twentyFour = require('../../utils/twenty_four.js')
const app = getApp()
import {
  evaluate
} from '../../utils/eval.min.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user_data: {},
    user_rank: {},
    pointer: 0, //计数器
    skip_idx: 0,
    is_time: 0,
    solution: 0,
    answer_list_left: [],
    answer_list_right: [],
    is_ratio: null,
    test: [],
    test_list: [],
    is_idx_0: false, //选中卡片
    is_idx_1: false, //选中卡片
    is_idx_2: false, //选中卡片
    is_idx_3: false, //选中卡片
    is_last_symbol: false,
    is_last_number: false,
    last_pick: '',
    pick_math: '',
    ratio_score: 0,
    pick_methods: [],
    is_show: false,
    is_share: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let test = options.test
    if (test) { //是否分享
      test = test.split(',')
      this.getAnswerList(test, () => {
        this.setData({
          is_share: true,
          test: test
        })
      })
    } else {
      this.setData({
        user_data: app.global_data.user_data
      })
      this.getRank()
      this.setInetval()
      this.setTest()
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '算二十四点',
      path: `/pages/twenty_four_math/twenty_four_math?test=${this.data.test}`
    }
  },
  /* 
  朋友圈
  */
  onShareTimeline() {
    return {
      query: `test=${this.data.test}`
    }
  },
  /* 获取排行 */
  getRank() {
    wx.cloud.callFunction({
      name: 'runDb',
      data: {
        type: 'get_detail',
        collection: 'twenty_four_math',
        is_where: {
          "user_openid": this.data.user_data.openid
        },
      },
      complete: res => {
        let detail = res.result.data[0]
        // console.log(detail)
        this.setData({
          user_rank: detail
        })
      }
    })
  },
  /* 启动计时器 */
  setInetval() {
    this.data.setInter = setInterval(() => {
      let numVal = this.data.is_time + 1
      this.setData({
        is_time: numVal
      })
    }, 1000)
  },
  /* 清除计时器 */
  clearInetval() {
    clearInterval(this.data.setInter)
  },
  /* 获取答案 */
  getAnswerList(test, cb) {
    let is_test = twentyFour.main(test)
    // console.log(is_test)
    let answer_list = is_test.arr
    console.log(answer_list[0])
    let list0 = []
    let list1 = []
    answer_list.forEach((item, idx) => {
      if (idx % 2) {
        list1.push(item)
      } else {
        list0.push(item)
      }
    })
    this.setData({
      answer_list_left: list0,
      answer_list_right: list1,
      solution: is_test.arr.length,
      is_ratio: is_test.ratio
    })
    if (cb) {
      cb()
    }
  },
  /* 生成题目 */
  setTest() {
    if (this.data.pointer < 5) {
      let test = []
      for (let i = 0; i < 4; i++) {
        test.push(Math.floor(Math.random() * 13 + 1))
      }
      let is_test = twentyFour.main(test)
      // console.log(is_test)
      if (is_test) {
        this.getAnswerList(test, () => {
          this.setData({
            test,
            pointer: this.data.pointer + 1,
            test_list: [...this.data.test_list, test],
          })
        })
      } else {
        this.setTest()
      }
    } else {
      this.getScore()
    }
  },
  /* 输入数字 */
  clickCard(e) {
    if (this.data.is_last_number) {
      wx.vibrateLong({})
      return
    }
    let {
      idx,
    } = e.currentTarget.dataset
    idx = +idx
    switch (idx) {
      case 0:
        if (!this.data.is_idx_0) {
          this.setData({
            is_idx_0: true,
            is_last_symbol: false,
            is_last_number: true,
            pick_math: this.data.pick_math + this.data.test[idx],
            pick_methods: [...this.data.pick_methods, idx],
          })
        }
        break
      case 1:
        if (!this.data.is_idx_1) {
          this.setData({
            is_idx_1: true,
            is_last_symbol: false,
            is_last_number: true,
            pick_math: this.data.pick_math + this.data.test[idx],
            pick_methods: [...this.data.pick_methods, idx],
          })
        }
        break
      case 2:
        if (!this.data.is_idx_2) {
          this.setData({
            is_idx_2: true,
            is_last_symbol: false,
            is_last_number: true,
            pick_math: this.data.pick_math + this.data.test[idx],
            pick_methods: [...this.data.pick_methods, idx],
          })
        }
        break
      case 3:
        if (!this.data.is_idx_3) {
          this.setData({
            is_idx_3: true,
            is_last_symbol: false,
            is_last_number: true,
            pick_math: this.data.pick_math + this.data.test[idx],
            pick_methods: [...this.data.pick_methods, idx],
          })
        }
        break
      default:
        break
    }
  },
  /* 输入符号 */
  clickMathCard(e) {
    let {
      idx,
    } = e.currentTarget.dataset
    if (idx == "21" || idx == "22") {
      this.setData({
        is_last_symbol: false,
      })
    } else {
      if (this.data.is_last_symbol) {
        wx.vibrateLong({})
        return
      }
      this.setData({
        is_last_symbol: true,
      })
    }
    let is_idx
    switch (idx) {
      case '11':
        is_idx = '+'
        break
      case '12':
        is_idx = '-'
        break
      case '13':
        is_idx = '×'
        break
      case '14':
        is_idx = '÷'
        break
      case '21':
        is_idx = '('
        break
      case '22':
        is_idx = ')'
        break
      default:
        break
    }
    this.setData({
      is_last_number: false,
      pick_math: this.data.pick_math + is_idx,
      pick_methods: [...this.data.pick_methods, idx],
    })
  },
  /* 后退 */
  clickBackSpace() {
    let is_methods = this.data.pick_methods
    let is_pop = is_methods.pop()
    let is_length = is_methods.length
    let is_last
    if (is_length) {
      let is_pick = this.pickLabel(is_methods)
      is_last = is_methods[is_length - 1]
      // console.log(is_last)
      switch (+is_last) {
        case 0:
        case 1:
        case 2:
        case 3:
          this.setData({
            is_last_symbol: false,
            is_last_number: true,
          })
          break
        case 21:
        case 22:
          this.setData({
            is_last_symbol: false,
            is_last_number: false,
          })
          break
        case 11:
        case 12:
        case 13:
        case 14:
          this.setData({
            is_last_symbol: true,
            is_last_number: false,
          })
          break
        default:
          break
      }
      this.setData({
        last_pick: is_last,
        pick_math: is_pick
      })
    } else {
      this.setData({
        last_pick: '',
        pick_math: '',
        is_last_symbol: false,
        is_last_number: false,
      })
    }
    this.setData({
      pick_methods: is_methods
    })
    switch (+is_pop) {
      case 0:
        this.setData({
          is_idx_0: false,
        })
        break
      case 1:
        this.setData({
          is_idx_1: false,
        })
        break
      case 2:
        this.setData({
          is_idx_2: false,
        })
        break
      case 3:
        this.setData({
          is_idx_3: false,
        })
        break
      default:
        break
    }
  },
  /* 答案转换 */
  pickLabel(array) {
    let is_methods = array
    let is_pick = ''
    for (let i = 0; i < is_methods.length; i++) {
      let label = is_methods[i]
      switch (+is_methods[i]) {
        case 0:
          label = this.data.test[0]
          break
        case 1:
          label = this.data.test[1]
          break
        case 2:
          label = this.data.test[2]
          break
        case 3:
          label = this.data.test[3]
          break
        case 11:
          label = '+'
          break
        case 12:
          label = '-'
          break
        case 13:
          label = '×'
          break
        case 14:
          label = '÷'
          break
        case 21:
          label = '('
          break
        case 22:
          label = ')'
          break
        default:
          break
      }
      is_pick += label
    }
    return is_pick
  },
  /* 验证答案 */
  async clickConfirm() {
    if (!this.data.is_idx_0 || !this.data.is_idx_1 || !this.data.is_idx_2 || !this.data.is_idx_3) {
      wx.showToast({
        title: '数字卡片需用完!',
        icon: 'none'
      })
      wx.vibrateLong({})
      return
    }
    let is_pick = this.data.pick_math.toString()
    is_pick = is_pick.replace(/×/g, "*").replace(/÷/g, "/")
    let is_answer
    try {
      is_answer = await this.getEval(is_pick) === 24
    } catch (error) {
      wx.showToast({
        title: '等式不成立,请重试',
        icon: 'none'
      })
      this.resetPick()
      return
    }
    // console.log(is_answer)
    if (is_answer) {
      wx.showToast({
        title: '计算成功',
        icon: 'seccess'
      })
      if (this.data.is_share) {
        return
      }
      let ratio = +this.data.is_ratio
      this.setData({
        ratio_score: this.data.ratio_score + ratio,
      })
      this.resetPick(() => {
        this.setTest()
      })
    } else {
      wx.showToast({
        title: '计算失败',
        icon: 'none'
      })
      wx.vibrateLong({})
    }
  },
  /* 获得计算结果 */
  getEval(str) {
    return new Promise((resolve, reject) => {
      let ret = evaluate(str)
      if (ret) {
        resolve(ret)
      } else {
        reject('error')
      }
    })
  },
  /* 查看答案 */
  clickAnswerList() {
    this.clearInetval()
    let that = this
    let content = ""
    if (this.data.is_share) {
      content = "查看解法后将退出小游戏"
    } else {
      content = "查看解法后将跳过本题"
    }
    wx.showModal({
      content: content,
      success(res) {
        if (res.confirm) {
          that.setData({
            is_show: true
          })
        } else {
          that.setInetval()
        }
      }
    })
  },
  /* 关闭答案 */
  closeShow() {
    if (this.data.is_share) {
      wx.reLaunch({
        url: '/pages/home/home',
      })
    } else {
      this.setInetval()
      this.setData({
        is_show: false
      })
      this.skipTest()
    }
  },
  /* 跳过题目 */
  skipTest() {
    let list = this.data.test_list
    list.pop()
    this.setData({
      skip_idx: this.data.skip_idx + 1,
      pointer: this.data.pointer - 1,
      test_list: list,
    })
    this.resetPick(() => {
      this.setTest()
    })
  },
  /* 点击跳过 */
  clickSkipTest() {
    let that = this
    wx.showModal({
      title: '确认直接跳过吗',
      content: '点击本题解法可以查看答案!',
      success(res) {
        if (res.confirm) {
          that.skipTest()
        }
      }
    })
  },
  /* 直接上传 */
  clickInsert() {
    let that = this
    wx.showModal({
      title: '确认直接上传吗',
      content: '点击本题解法可以查看答案!',
      success(res) {
        if (res.confirm) {
          that.getScore()
        }
      }
    })
  },
  /* 生成成绩 */
  getScore() {
    this.clearInetval()
    let that = this
    let data = {
      user_openid: this.data.user_data.openid,
      score: this.data.ratio_score,
      score_time: this.data.is_time,
      update_time: app.dayjs().valueOf()
    }
    // console.log(data)
    if (this.data.user_rank) {
      if (data.score < this.data.user_rank.score) {
        wx.showToast({
          title: '成绩未提升,请努力哦!',
          icon: 'none'
        })
        wx.redirectTo({
          url: '/pages/minigame_list/minigame_list',
        })
      } else if (data.score == this.data.user_rank.score && data.score_time > this.data.user_rank.score_time) {
        wx.showToast({
          title: '成绩未提升,请努力哦!',
          icon: 'none'
        })
        wx.redirectTo({
          url: '/pages/minigame_list/minigame_list',
        })
      } else {
        wx.cloud.callFunction({
          name: "runDb", //云函数名
          data: {
            type: 'update_detail', //指定操作类型
            collection: 'twenty_four_math', //修改的集合名称
            is_where: {
              "user_openid": that.data.user_data.openid
            },
            data //更新的数据
          },
          success: res => {
            wx.showToast({
              title: '更新得分成功',
              duration: 500,
              success: res => {
                wx.redirectTo({
                  url: '/pages/minigame_list/minigame_list'
                })
              }
            })
          },
          fail: err => {
            console.error('更新得分失败', err)
          }
        })
      }
    } else {
      wx.cloud.callFunction({
        name: "runDb", //云函数名
        data: {
          type: 'insert', //指定操作类型
          collection: 'twenty_four_math', //修改的集合名称
          data //更新的数据
        },
        success: res => {
          wx.showToast({
            title: '上传得分成功',
            duration: 500,
            success: res => {
              wx.redirectTo({
                url: '/pages/minigame_list/minigame_list'
              })
            }
          })
        },
        fail: err => {
          console.error('上传得分失败', err)
        }
      })
    }
  },
  /* 重置选项 */
  resetPick(cb) {
    this.setData({
      is_last_symbol: false,
      is_last_number: false,
      is_idx_0: false, //选中卡片
      is_idx_1: false, //选中卡片
      is_idx_2: false, //选中卡片
      is_idx_3: false, //选中卡片
      last_pick: '',
      pick_math: '',
      pick_methods: [],
    })
    if (cb) {
      cb()
    }
  },
})